<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择角色状态"
          clearable
          style="width: 100%;"
        >
          <el-option
            v-for="(value, key) in statusInfo"
            :key="key"
            :label="value"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:platformRole:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="platformRoleList">
      <el-table-column :formatter="defaultTableColumnDate" label="序号" align="center" type="index" />
      <el-table-column :formatter="defaultTableColumnDate" label="角色名称" align="center" prop="roleName" />
      <el-table-column :formatter="defaultTableColumnDate" label="关联人数" align="center" prop="userCount">
        <template slot-scope="scope">
          <el-link type="primary" @click="getAccount(scope.row.id)">{{ scope.row.userCount }}</el-link>
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="更新人" align="center" prop="updateBy" />
      <el-table-column :formatter="defaultTableColumnDate" label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="角色状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ statusInfo[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:platformRole:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row, $index)"
            v-hasPermi="['system:platformRole:remove']"
          >{{scope.row.status=='0'?'禁用':'启用'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台角色对话框 -->
    <el-dialog destroy-on-close :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <!-- <el-form-item label="角色权限字符串" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入角色权限字符串" />
        </el-form-item> -->
        <el-form-item label="功能权限">
          <el-tabs v-model="menuType" type="card">
            <el-tab-pane label="WEB端权限" name="1">
            </el-tab-pane>
            <el-tab-pane label="小程序权限" name="2">
            </el-tab-pane>
            <el-tree
              class="tree-border"
              v-show="menuType=='1'"
              :data="menuOptions1"
              show-checkbox
              ref="pcMenu"
              node-key="menuId"
              :check-strictly="isBack"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            ></el-tree>
            <el-tree
              class="tree-border"
              v-show="menuType=='2'"
              :data="menuOptions2"
              show-checkbox
              ref="appletMenu"
              node-key="menuId"
              :check-strictly="false"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            ></el-tree>
          </el-tabs>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看关联名单 -->
    <el-dialog destroy-on-close title="查看关联名单" :visible.sync="accountopen" width="1000px" append-to-body>
      <el-table style="width: 100%;" :data="accountList">
        <el-table-column :formatter="defaultTableColumnDate" prop="userName" label="账号"></el-table-column>
        <el-table-column :formatter="defaultTableColumnDate" prop="lastLoginTime" label="最后登录时间"></el-table-column>
        <el-table-column :formatter="defaultTableColumnDate" label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="removeUser(scope.row)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="accountopen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlatformRole, getPlatformRole, changeStatus, addPlatformRole, updatePlatformRole, 
  getSystemAllMenu, getAppletAllMenu, getAccountByRole, deleteAccount } from "@/api/system/platformRole";

let menuFlag1 = false
let menuFlag2 = false
export default {
  name: "PlatformRole",
  data() {
    return {
      menuType: '1',
      accountList: [],
      roleId: '',
      menuExpand: false,
      menuNodeAll: false,
      isBack: true,
      menuOptions1: [],
      menuOptions2: [],
      defaultProps: {
        children: "itemList",
        label: "menuName"
      },
      statusInfo: {
        '0': '启用',
        '1': '禁用',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台角色表格数据
      platformRoleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      accountopen: false,
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null,
        roleKey: null,
        roleSort: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "角色状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getMenuList()
  },
  methods: {
    getAccount(id) {
      this.$modal.loading()
      this.roleId = id
      getAccountByRole({id}).then(res => {
        this.$modal.closeLoading()
        this.accountList = res.data
        this.accountopen = true
      })
    },
    removeUser(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除关联账号"' + row.userName + '"的数据项？').then(function() {
        return deleteAccount({id, roleId: this.roleId});
      }).then(() => {
        this.getAccount();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys(name) {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs[name].getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs[name].getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    getMenuList() {
      getSystemAllMenu().then(response => {
        this.menuOptions1 = this.buildTree(response.data)
      })
      getAppletAllMenu().then(response => {
        this.menuOptions2 = this.buildTree(response.data)
      })
    },
    buildTree(data, rootId = '0') {
      const map = new Map();
      const result = [];

      // 初始化 map，每个节点预设 itemList 为 []
      data.forEach(item => {
        item.itemList = [];
        map.set(item.menuId, item);
      });

      data.forEach(item => {
        if (item.parentId === rootId) {
          result.push(item);
        } else {
          const parent = map.get(item.parentId);
          if (parent) {
            parent.itemList.push(item);
          } else {
            result.push(item);
          }
        }
      });
      return result;
    },
    /** 查询平台角色列表 */
    getList() {
      this.loading = true;
      listPlatformRole(this.queryParams).then(response => {
        this.platformRoleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roleName: null,
        roleKey: null,
        roleSort: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlatformRole(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.isBack = true;
        this.$nextTick(function() {
          this.$refs.pcMenu.setCheckedKeys(response.data.pcMenuList, true ,false);
          this.$refs.appletMenu.setCheckedKeys(response.data.appletMenuList, true ,false);
          this.isBack = false
        })
        this.title = "修改平台角色";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.pcMenuList = this.getMenuAllCheckedKeys('pcMenu');
          this.form.appletMenuList = this.getMenuAllCheckedKeys('appletMenu');
          if (this.form.id != null) {
            updatePlatformRole(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlatformRole(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row, index) {
      const id = row.id;
      this.$modal.confirm('是否确认修改平台角色编号为"' + index + '"的数据项的状态？').then(function() {
        return changeStatus({id, status: row.status=='0'?'1':'0'});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("修改成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/platformRole/export', {
        ...this.queryParams
      }, `platformRole_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
